package website.lucaswork.survey.mvc.validators;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import website.lucaswork.survey.core.services.UserService;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = UniqueEmail.UniqueEmailValidator.class)
@Target({ElementType.FIELD, ElementType.METHOD})
public @interface UniqueEmail {
    String message() default "Email is duplicated";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    public class UniqueEmailValidator implements ConstraintValidator<UniqueEmail, String> {

        @Autowired
        UserService userService;

        @Override
        public void initialize(UniqueEmail name) {

        }

        @Override
        public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
            try {
                userService.findUserByEmail(s);
            } catch(UsernameNotFoundException e) {
                return true;
            }
            return false;
        }
    }
}
